<template>
  <div>

    <!-- 添加面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 添加卡片视图-->
    <el-card>
      <!-- 定义栅格 -->
      <el-row :gutter="20">
        <!-- 添加输入框-->
        <el-col :span="12">
          <el-input placeholder="按照用户名搜索" v-model="queryUserInfo.query" @clear="getUserList" clearable>
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 定义表格数据 stripe 隔行变色-->
      <el-table :data="rows" stripe style="width: 100%" border>
        <!-- 添加索引列-->
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="phone" label="电话号"></el-table-column>
        <el-table-column prop="email" label="邮箱地址"></el-table-column>
        <el-table-column prop="role.roleName" label="角色"></el-table-column>
        <el-table-column label="状态">
          <!-- 定义作用域插槽 展现数据     scope.row展现行级元素 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" active-color="#13ce66" inactive-color="#ff4949"
              @change="changeStatus(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <!--
            由于操作需要传递用户ID值,所以可以使用作用域插槽的方式实现
            :enterable="false" 鼠标是否可进入到 tooltip中
          -->
          <template slot-scope="scope">
            <!-- 定义三个按钮-->
            <el-tooltip class="item" effect="dark" content="修改" placement="top" :enterable="false">
              <!-- 点击编辑按钮将数据信息传给方法-->
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showUpdateDialogVisible(scope.row)">
              </el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 定义分页操作
        handleSizeChange    条数改变时触发
        handleCurrentChange 页数改变时触发
        current-page        绑定当前页数
        page-sizes          表示分页条数选项
        page-size           每页多少条
        layout              显示组件个数
        total               总记录数

      -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryUserInfo.pageNum" :page-sizes="[5, 10, 20, 40]" :page-size="queryUserInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>

    </el-card>

    <!-- 定义新增对话框 -->
    <el-dialog title="新增用户" :visible.sync="addUserDialogVisible" width="50%" @close="addUserDialogClose">

      <!-- 对话框主体区域 定义用户提交表格  关于表单数据提交参数说明
          model: 表示需要提交的数据
          rules: 表单数据校验规则
          ref:   为form表单对象定义名称 方便以后调用
      -->
      <el-form :model="addUserModel" :rules="addUserRules" ref="ruleFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserModel.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserModel.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="密码确认" prop="password2">
          <el-input v-model="addUserModel.password2" type="password"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addUserModel.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserModel.email"></el-input>
        </el-form-item>
      </el-form>



      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 定义编辑对话框  定义关闭对话框之后数据重置-->
    <el-dialog title="编辑用户" :visible.sync="updateDialogVisible" width="50%" @close="updateDialogClose">

      <el-form :model="updateUserModel" :rules="addUserRules" ref="updateFormRef" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="updateUserModel.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="updateUserModel.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updateUserModel.email"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="分配角色" :visible.sync="setRoledialogVisible" width="50%" @close="closeRoleDialog">
      <p>用户ID: {{roleUserInfo.id}}</p>
      <p>用户名称: {{roleUserInfo.username}}</p>
      <p>用户角色: {{roleUserInfo.roleName}}</p>
      <p>分配角色:

         <!-- 定义下拉框-->
         <el-select v-model="roleUserInfo.roleId" placeholder="请选择">
           <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId">
           </el-option>
         </el-select>
      </p>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUserRole">确 定</el-button>
      </span>
    </el-dialog>




  </div>
</template>

<script>
  export default {
    //定义钩子函数 created
    created() {
      //默认条件下初始化列表数据
      this.getUserList()
    },
    data() {

      //校验邮箱规则
      const checkEmail = (rule, value, callback) => {
        //定义邮箱的正则表达式  JS中用/来表示正则表达式的开始和结束
        const emailRege = /^[a-zA-Z0-9-_]+@[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+$/
        if (emailRege.test(value)) {
          //表示邮箱合法 正确返回
          return callback()
        }
        callback(new Error('请填写正确的邮箱地址'))
      }

      //校验手机号的邮箱规则
      const checkPhone = (rule, value, callback) => {

        //定义校验手机号的正则语法
        const phoneRege = /^1[34578][0-9]{9}$/
        if (phoneRege.test(value)) {

          return callback()
        }
        callback(new Error('请填写正确的手机号'))

      }

      //校验用户密码是否一致
      const checkPassword = (rule, value, callback) => {
        if (this.addUserModel.password2 !== '') {
          if (value !== this.addUserModel.password2)
            callback(new Error('两次输入的密码不一致'))
        }
        callback()
      }

      const checkPassword2 = (rule, value, callback) => {
        if (value === this.addUserModel.password) return callback()
        callback(new Error('两次输入的密码不一致'))
      }




      return {
        //定义提交参数对象
        queryUserInfo: {
          query: '', //定义查询参数
          pageNum: 1,
          pageSize: 10
        },
        //获取记录总数
        total: 0,
        //获取当前页数据
        rows: [],
        //定义新增对话框状态
        addUserDialogVisible: false,
        //定义修改对话框状态
        updateDialogVisible: false,

        //定义用户新增数据模型
        addUserModel: {
          username: '',
          password: '',
          password2: '',
          email: '',
          phone: ''
        },
        //定义修改用户数据模型
        updateUserModel: {

        },

        //添加表单校验规则对象
        addUserRules: {

          //校验用户名   trigger 触发时机,在失去焦点时触发
          username: [{
              required: true,
              message: '请输入用户名称',
              trigger: 'blur'
            },
            {
              min: 5,
              max: 40,
              message: '长度在 5 到 40 个字符',
              trigger: 'blur'
            }
          ],
          password: [{
              required: true,
              message: '请输入用户密码',
              trigger: 'blur'
            },
            {
              min: 5,
              max: 40,
              message: '长度在 5 到 40 个字符',
              trigger: 'blur'
            },
            {
              validator: checkPassword,
              trigger: 'blur'
            }
          ],
          password2: [{
              required: true,
              message: '请输入用户密码',
              trigger: 'blur'
            },
            {
              min: 5,
              max: 40,
              message: '长度在 5 到 40 个字符',
              trigger: 'blur'
            },
            {
              validator: checkPassword2,
              trigger: 'blur'
            }
          ],
          phone: [{
              required: true,
              message: '请输入用户电话',
              trigger: 'blur'
            },
            {
              min: 5,
              max: 40,
              message: '长度在 5 到 40 个字符',
              trigger: 'blur'
            },
            {
              validator: checkPhone,
              trigger: 'blur'
            }
          ],
          email: [{
              required: true,
              message: '请输入用户邮箱',
              trigger: 'blur'
            },
            {
              min: 5,
              max: 40,
              message: '长度在 5 到 40 个字符',
              trigger: 'blur'
            },
            {
              validator: checkEmail,
              trigger: 'blur'
            }
          ]
        },
        setRoledialogVisible: false,

        //定义添加角色的用户对象
        roleUserInfo: {},
        roleList: [],
        roleId: ''

      }
    },
    methods: {
      async getUserList() {
        const {
          data: result
        } = await this.$http.get('/user/list', {
          params: this.queryUserInfo
        })
        if (result.status !== 200) return this.$message.error('查询用户失败');
        this.total = result.data.total;
        this.rows = result.data.rows;
      },
      //条数改变触发事件
      handleSizeChange(size) {
        //进行分页操作
        this.queryUserInfo.pageSize = size
        this.getUserList();
      },
      //页面改变触发事件
      handleCurrentChange(current) {
        this.queryUserInfo.pageNum = current
        this.getUserList();
      },
      async changeStatus(row) {
        //发起ajax请求实现状态信息修改
        const {
          data: result
        } = await this.$http.put('/user/updateStatus', {
          id: row.id,
          status: row.status
        })
        if (result.status !== 200) {
          //还原原来状态信息
          row.status = !row.status
          return this.$message.error('更新状态失败')
        }
        this.$message.success('更新用户状态成功')
      },
      addUserDialogClose() {
        this.$refs.ruleFormRef.resetFields()
      },

      //定义添加用户的方法
      addUser() {
        this.$refs.ruleFormRef.validate(async valid => {
          //console.log("检验是否成功:"+valid)
          if (!valid) return
          //发起ajax请求 实现添加用户操作
          const {
            data: result
          } = await this.$http.post('/user/addUser', this.addUserModel)
          if (result.status !== 200) return this.$message.error('用户新增失败')
          this.$message.success('用户新增成功')
          //成功之后应该将对话窗口关闭
          this.addUserDialogVisible = false
          //之后应该刷新表格数据
          this.getUserList()
        })
      },

      //定义修改方法
      async showUpdateDialogVisible(row) {
        this.updateDialogVisible = true;
        //动态获取想要的数据
        //this.addUserModel = row;
        let id = row.id
        //方式1: 根据ID发起Ajax请求 获取用户信息  通过params参数获取数据
        let {
          data: result
        } = await this.$http.get('/user/getUserById', {
          params: {
            'id': id
          }
        })
        if (result.status !== 200) return this.$message.error('查询用户失败')
        this.updateUserModel = result.data
        console.log(this.updateUserModel)
        //方法2: 根据已有数据从页面中获取用户信息
      },

      //定义表格数据关闭之后,重置数据
      updateDialogClose() {
        this.$refs.updateFormRef.resetFields()
      },
      updateUser() {
        //实现用户数据更新操作
        this.$refs.updateFormRef.validate(async validate => {
          if (!validate) return
          const {
            data: result
          } = await this.$http.put('/user/updateUser', {
            "id": this.updateUserModel.id,
            "email": this.updateUserModel.email,
            "phone": this.updateUserModel.phone
          })
          if (result.status !== 200) return this.$message.error("用户更新失败")
          this.$message.success("用户更新成功")
          //关闭对话框
          this.updateDialogVisible = false
          //重新获取列表信息
          this.getUserList()
        })
      },
      deleteUser(id) {
        this.$confirm('删除ID为 ' + id + ' 的用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {

          //发起ajax请求实现删除操作
          const {
            data: result
          } = await this.$http.delete("/user/deleteUserById", {
            "params": {
              "id": id
            }
          })
          if (result.status !== 200) return this.$message.error("删除用户失败")
          this.$message.success("删除数据成功")
          this.getUserList()
        }).catch(() => {
          this.$message.info("取消删除操作")
        })
      },
      //分配用户角色
      async setRole(user) {
        this.roleUserInfo.username = user.username
        this.roleUserInfo.roleName = user.role.roleName
        this.roleUserInfo.id = user.id;
        //发起ajax请求获取全部的角色列表数据
        const {
          data: result
        } = await this.$http.get("/user/getRoleList")
        if (result.status !== 200) {
          return this.$message.error("查询用户列表失败")
        }
        this.roleList = result.data
        this.setRoledialogVisible = true
      },
      async saveUserRole(){
        let userId = this.roleUserInfo.id
        let roleId = this.roleUserInfo.roleId
        const {data: result}  = await this.$http.put("/user/saveUserRole","userId="+userId+"&roleId="+roleId)
        if(result.status !==200) return this.$message.error("更新角色失败")
        this.$message.success("更新角色成功")
        this.getUserList();
        this.setRoledialogVisible = false
      },
      //关闭操作时,需要清空数据
      closeRoleDialog(){
        this.roleId = ''
        this.roleUserInfo = {}
      }
    }
  }
</script>

<style lang="less" scoped>

</style>
